package com.example.jimuyutabletcontrol.fragment;


import android.app.Activity;
import android.content.Context;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.example.jimuyutabletcontrol.MapApplication;
import com.example.jimuyutabletcontrol.R;
import com.example.jimuyutabletcontrol.activity.ControlActivity;
import com.example.jimuyutabletcontrol.adapter.navigation_dialog.NavigationTaskDialogAdapter;
import com.example.jimuyutabletcontrol.bean.MakeTaskMapPoint;
import com.example.jimuyutabletcontrol.bean.NavigationDialogTaskInfo;
import com.example.jimuyutabletcontrol.bean.UnperformedTask;
import com.example.jimuyutabletcontrol.dialog.SendNavigationTaskDialogFragment;
import com.example.jimuyutabletcontrol.network.udp.UdpSocket;
import com.example.jimuyutabletcontrol.port.TaskFileNameCallback;
import com.example.jimuyutabletcontrol.utils.MapUtil;
import com.example.jimuyutabletcontrol.utils.TaskUtil;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class NavigationDialogTaskFragment extends Fragment {

    private static final String KEY_PARAM = "key_param_" + NavigationDialogTaskFragment.class.getSimpleName();

    public static NavigationDialogTaskFragment getInstance(String imei) {
        NavigationDialogTaskFragment f = new NavigationDialogTaskFragment();
        Bundle params = new Bundle();
        params.putString(KEY_PARAM, imei);
        f.setArguments(params);
        return f;
    }

    private View rootView;

    private RecyclerView mRecyclerView;

    private NavigationTaskDialogAdapter taskDialogAdapter;

    private List<NavigationDialogTaskInfo> infos;

    private String imei;

    private Context mContext;

    private TaskFileNameCallback fileNameCallback;

    private NavigationDialogTaskFragment() {
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        this.mContext = context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        imei = getArguments().getString(KEY_PARAM);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_navigation_dialog_task, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        this.rootView = view;
        initView();
        setAdapter();
        setListener();
        getData();
    }

    private void getData() {
        MapApplication.refreshFileDataWithImei(imei, false);
    }

    private void setListener() {
        MapApplication.setFileTaskCallback(fileNameCallback = taskFiles -> refreshData(taskFiles.get(imei)));
        taskDialogAdapter.setOnNavigationTaskDialogListener(this::showSendTaskDialog);
    }

    private void showSendTaskDialog(int position){
        String url = TaskUtil.getAuvTaskUrlWithName(imei,infos.get(position).taskName);
        if (TextUtils.isEmpty(url)){
            url = TaskUtil.getTaskUrlWithName(infos.get(position).taskName);
        }
        double totalTime;
        if (TextUtils.isEmpty(url)){
            totalTime = -1;
        } else {
            List<MakeTaskMapPoint.PackageAuxiliaryPoint> list = TaskUtil.getTaskWithTaskFile(url);
            totalTime = MapUtil.getTotalTime(list);
        }
        SendNavigationTaskDialogFragment dialog = SendNavigationTaskDialogFragment.getInstance(infos.get(position),totalTime);
        dialog.setOnSendNavigationTaskDialogListener(taskInfo -> {
            UnperformedTask unperformedTask = UnperformedTask.getInstance();
            List<String> strs = new ArrayList<>();
            strs.add(imei);
            unperformedTask.setNavigation(taskInfo.taskName, taskInfo.maxTime,taskInfo.testParam,strs);
            Toast.makeText(mContext,"设置成功",Toast.LENGTH_SHORT).show();
            if (mContext instanceof ControlActivity){
                ((ControlActivity)mContext).setUnperfornedTask();
            }
//            UdpSocket.getInstance().sendMessage("B"+imei+"gps," +"testParam:"+
//                    taskInfo.testParam+",max_duration_of_voyage:"+taskInfo.maxTime+",fileName:"+taskInfo.taskName);
        });
        dialog.show(getChildFragmentManager(),"SendNavigationTaskDialogFragment");
    }


    private void refreshData(List<String> list) {
        if (null == list) return;
        ((Activity) mContext).runOnUiThread(() -> {
            infos.clear();
            for (String str : list) {
                NavigationDialogTaskInfo info = new NavigationDialogTaskInfo();
                info.taskName = str;
                infos.add(info);
            }
            taskDialogAdapter.notifyDataSetChanged();
        });
    }

    private void setAdapter() {
        infos = new ArrayList<>();
        taskDialogAdapter = new NavigationTaskDialogAdapter(infos);
        mRecyclerView.setAdapter(taskDialogAdapter);
    }

    private void initView() {
        mRecyclerView = rootView.findViewById(R.id.mRecyclerView);
    }

    @Override
    public void onDestroy() {
        if (null != fileNameCallback) {
            MapApplication.removeFileTaskCallback(fileNameCallback);
        }
        super.onDestroy();
    }
}
